# -*- coding: utf-8 -*-
import numpy
from sklearn import datasets     #设置数据集
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier  #选择临近的点做邻居，模拟数据预测值
import pickle

iris = datasets.load_iris()  #导入鸢尾花数据
iris_x = iris.data
iris_y = iris.target

print(iris_x[:2,:])
#输出是
#   [[ 5.1  3.5  1.4  0.2]
#   [ 4.9  3.   1.4  0.2]]
#这是两个simple，里面是属性,比如花的直径

print(iris_y)
#输出是
#[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
#1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
#2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
#2 2]
#0代表0这种花,1代表1这种花

#下面开始分测试数据和学习数据,这样分不会产生认为的误差

x_train,x_test,y_train,y_test = train_test_split(iris_x,iris_y,test_size=0.3)  #其中30%用来测试，这个过程中数据会被打乱

print(y_train)

knn = KNeighborsClassifier()    #指定算法为分类
knn.fit(x_train,y_train)     #开始训练

print("训练结果：")
print(knn.predict(x_test))    #预测并查看训练结果
print(y_test)

#下面是保存模型的步骤
with open("test.pickle","wb") as f:
    pickle.dump(knn,f)               #保存knn这个模型到test.pickle


with open("test.pickle","rb") as f:
    knn2 = pickle.load(knn,f)               #加载
    print(knn.predict(x_test))
#or
from sklearn.externals import joblib
joblib.dump(knn,"test.pkl")   #保存
knn3 = joblib.load("test.pkl")  #加载

